package com.leinao.task;

import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.UncheckedTimeoutException;
import com.jcraft.jsch.JSchException;
import com.leinao.config.EnvironmentConfig;
import com.leinao.images.dao.ImagesMapper;
import com.leinao.images.dto.ImageInfo;
import com.leinao.images.dto.ImagesDto;
import com.leinao.images.service.impl.ImagesServiceImpl;
import com.leinao.util.SSHClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.xnio.Result;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

import static java.lang.Thread.sleep;

/**
 * @description: 定时处理dockerfile文件
 * @author: 曹阳
 * @date: 2019-05-16 09:13
 */
@Component
@Configuration
@EnableScheduling
public class ScheduleTask {
    @Autowired
    EnvironmentConfig envConfig;
    @Autowired
    private SSHClient sshClient;
    @Autowired
    private ImagesMapper imagesMapper;

    private Logger logger = LoggerFactory.getLogger(ScheduleTask.class);

    @Scheduled(cron = "0/10 * * * * ?")
    private void configureTasks() {
        logger.info("执行静态定时任务时间: " + LocalDateTime.now());
        List<ImagesDto> images = imagesMapper.getUserImageByStatus(1);
        if(!CollectionUtils.isEmpty(images)) {
            sshClient.setHost(envConfig.getSshHost()).setPort(envConfig.getSshPort()).setUsername(envConfig.getSshUser()).setPassword(envConfig.getSshPwd());
            sshClient.login();
            ExecutorService executorService = Executors.newFixedThreadPool(3);
            for (int i = 0; i < images.size(); i++) {
                final ImagesDto image = images.get(i);
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        SimpleTimeLimiter timeLimiter = new SimpleTimeLimiter();
                        ImageCallable work = new ImageCallable(sshClient, envConfig, imagesMapper, image);
                        long now = System.currentTimeMillis();
                        try {
                            timeLimiter.callWithTimeout(work, 30, TimeUnit.MINUTES, false);
                        } catch (UncheckedTimeoutException e) {
                            logger.info("执行静态定时任务超时,镜像名:{}, 耗时: {}s：", image.getName(), (System.currentTimeMillis()  - now) / 1000);
                        } catch (Exception e) {
                            logger.info("执行静态定时任务异常,镜像名:{}, 耗时: {}s, 异常信息: {}", image.getName(), (System.currentTimeMillis()  - now) / 1000, e);
                        }
                    }
                });
            }

            // 一定要调用这个方法，不然executorService.isTerminated()永远不为true
            executorService.shutdown();

            // 等待所有任务都结束了继续执行
            while(true){
                try {
                    if(executorService.isTerminated()){
                        logger.info("所有的子线程都结束了！");
                        break;
                    }
                    Thread.sleep(1000 * 60);
                } catch (Exception e){
                    logger.info("等待所有任务都结束出现异常", e);
                }
            }
        }
    }
}
